/*
 * Name        : TaskManager.java
 * Classes     : TaskManager
 * Version     : 1.0
 * Date        : 2013-08-29
 *
 * Copyright 2013 CMCC.  All rights reserved.
 * This material, including documentation and any related computer
 * programs, is protected by copyright controlled by CMCC.  All
 * rights are reserved.  Copying, including reproducing, storing,
 * adapting or translating, any or all of this material requires the
 * prior written consent of CMCC.  This material also contains
 * confidential information which may not be disclosed to others
 * without the prior written consent of CMCC.
 */

package com.xgkj.diyiketang.http.engine;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.util.SparseArray;

/**
 * Class Name : TaskManager 
 * Author : Huang xiao qing 
 * Date : 13-9-3 
 * Description :
 */
public class TaskManager {

    private SparseArray<BaseTask> mTaskMap;

    private static final int CORE_POOL_SIZE = 3;

    private ExecutorService mService;

    public TaskManager() {
        mTaskMap = new SparseArray<BaseTask>();
        mService = Executors.newScheduledThreadPool(CORE_POOL_SIZE);
    }

    /**
     * Add a task to the current thread pool, Returns the task id , or -1 if add failed.
     * 
     * @param   task
     * @return  the task id , or -1 if add failed.
     */
    public int addTask(BaseTask task) {
        if (task != null) {
            synchronized (mTaskMap) {
                mTaskMap.put(task.mId, task);
                mService.submit(task);
            }
            return task.mId;
        } else {
            return -1;
        }
    }

    /**
     * Cancel the task which has been added, if canceled it will not has any call-back notice.
     * 
     * @param  taskId
     */
    public void cancelTask(int taskId) {
        synchronized (mTaskMap) {
            BaseTask task = mTaskMap.get(taskId);
            if (task != null) {
                task.cancel();
                mTaskMap.delete(taskId);
            }
        }
    }

    public BaseTask findTask(int taskId) {
        return mTaskMap.get(taskId);
    }
}
